package com.university.trade.controller.admin;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.university.trade.entity.Blogger;
import com.university.trade.service.BloggerService;
import com.university.trade.util.CryptographyUtil;
import com.university.trade.util.DateUtil;
import com.university.trade.util.PropertiesUtil;
import com.university.trade.util.RequestUtil;
import com.university.trade.util.ResponseUtil;
import com.university.trade.util.StringUtil;
import com.university.trade.util.SystemConstantData;

import net.sf.json.JSONObject;

/**
 * 管理员博主Controller层
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/admin/blogger")
public class BloggerAdminController {

	@Resource
	private BloggerService bloggerService;
	
	/**
	 * 修改博主信息
	 * @param file1
	 * @param blogger
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
	public String save(@RequestParam("imageFile") MultipartFile imageFile,Blogger blogger,HttpServletRequest request,HttpServletResponse response)throws Exception{
		if(!imageFile.isEmpty()){
			String filePath = request.getSession().getServletContext().getRealPath("/");
			//String filePath = request.getContextPath();
			String imageName=DateUtil.getCurrentDateStr()+"."+imageFile.getOriginalFilename().split("\\.")[1];
			FileOutputStream fos = FileUtils.openOutputStream(new File(filePath+"static/userImages/"+imageName)); 
			IOUtils.copy( imageFile.getInputStream(), fos); 
			//FileUtils.copyFile(srcFile, new File(filePath+"static/userImages/"+imageName));
			//imageFile.transferTo(new File(filePath+"static/userImages/"+imageName));
			blogger.setImageName(imageName);
		}
		int resultTotal=bloggerService.update(blogger);
		StringBuffer result=new StringBuffer();
		if(resultTotal>0){
			result.append("<script language='javascript'>alert('修改成功！');</script>");
		}else{
			result.append("<script language='javascript'>alert('修改失败！');</script>");
		}
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 查询博主信息
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/find")
	public String find(HttpServletResponse response)throws Exception{
		Blogger blogger=bloggerService.find();
		JSONObject jsonObject=JSONObject.fromObject(blogger);
		ResponseUtil.write(response, jsonObject);
		return null;
	}
	
	/**
	 * 修改博主密码
	 * @param newPassword
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/modifyPassword")
	public String modifyPassword(String newPassword,HttpServletResponse response)throws Exception{
		Blogger blogger=new Blogger();
		PropertiesUtil systemProperties = new PropertiesUtil("/systemConfig.properties");
		String system_second_level_encrypt_str = systemProperties.getProperty("system_second_level_encrypt_str");
		blogger.setPassword(CryptographyUtil.md5(newPassword, system_second_level_encrypt_str));
		int resultTotal=bloggerService.update(blogger);
		JSONObject result=new JSONObject();
		if(resultTotal>0){
			result.put("success", true);
		}else{
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		return null;
	}
	/**
	 * 添加后台管理者
	 * @param newPassword
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addAdministrator")
	@ResponseBody
	public void addAdministrator(HttpServletRequest request,HttpServletResponse response)throws Exception{
		Map<String,Object> resultMap =  RequestUtil.verifyRequest(request);
		//如果返回结果为F,说明请求不正确,直接返回resultMap;如果返回结果为T,说明请求正常,做具体的局业务处理
		if(SystemConstantData.RESULT_OK.equals(resultMap.get("result"))){
			resultMap.put("result", SystemConstantData.RESULT_FAIL);
			// 具体业务处理
			String userName = RequestUtil.paramStringParse(request.getParameter("userName"));
			if(StringUtil.isEmpty(userName)){
				resultMap.put(SystemConstantData.PROMPT_MESSAGE, "用户登录名不能为空！");
				ResponseUtil.printJson(resultMap, response);
				return;
			}
			Blogger newBlogger = bloggerService.getByUserName(userName);
			if(null != newBlogger){
				resultMap.put(SystemConstantData.PROMPT_MESSAGE, "该用户名已经注册！");
				ResponseUtil.printJson(resultMap, response);
				return;
			}
			String password = RequestUtil.paramStringParse(request.getParameter("password"));
			String repassword = RequestUtil.paramStringParse(request.getParameter("repassword"));
			if("".equals(password) || "".equals(repassword)){
				resultMap.put(SystemConstantData.PROMPT_MESSAGE, "密码或重复密码不能为空！");
				ResponseUtil.printJson(resultMap, response);
				return;
			}
			if(!repassword.equals(password)){
				resultMap.put(SystemConstantData.PROMPT_MESSAGE, "两次输入密码不一致，请重新输入！");
				ResponseUtil.printJson(resultMap, response);
				return;
			}
			PropertiesUtil systemProperties = new PropertiesUtil("/systemConfig.properties");
			String system_second_level_encrypt_str = systemProperties.getProperty("system_second_level_encrypt_str");
			newBlogger = new Blogger();
			newBlogger.setUserName(userName);
			newBlogger.setPassword(CryptographyUtil.md5(request.getParameter("password"), system_second_level_encrypt_str));
			int resultTotal=bloggerService.save(newBlogger);
			if(resultTotal>0){
				resultMap.put("result", SystemConstantData.RESULT_OK);
				resultMap.put(SystemConstantData.PROMPT_MESSAGE, "后台管理员添加成功！");
				ResponseUtil.printJson(resultMap, response);
				return;
			}
		}
		resultMap.put(SystemConstantData.PROMPT_MESSAGE, "后台管理员新增失败！");
		ResponseUtil.printJson(resultMap, response);
		return;
	}
	
	/**
	 * 注销
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/logout")
	public String  logout()throws Exception{
		SecurityUtils.getSubject().logout();
		return "redirect:/login.jsp";
	}
}
